package com.uxsino.commons.utils;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PingUtils {
    private static final Logger LOG = LoggerFactory.getLogger(PingUtils.class);

    private static final boolean isWindows = isWindows();

    public static boolean ping(String ip, int retry, int timeOut) {
        BufferedReader in = null;
        Runtime r = Runtime.getRuntime();  // 将要执行的ping命令,此命令是windows格式的命令
        String pingCommand = "ping " + ip + " -n " + retry + " -w " + timeOut;
        if (!isWindows) {
            pingCommand = "ping " + ip + " -c " + retry + " -w " + (timeOut / 1000);
        }
        Process p = null;
        try {   // 执行命令并获取输出
            p = r.exec(pingCommand);
            if (p == null) {
                return false;
            }
            in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            int connectedCount = 0;
            String line = null;
            while ((line = in.readLine()) != null) {
                connectedCount += isWindows ? getCheckResult(line) : getCheckLinuxResult(line);
            }   // 如果出现类似=23ms TTL=62这样的字样,出现的次数=测试次数则返回真
            return connectedCount == retry;
        } catch (Exception ex) {
            LOG.error("【Ping ERROR 】", ex);   // 出现异常则返回假
            return false;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                LOG.warn("【Ping ERROR 】", e);
            }

            try {
                if (p != null) {
                    close(p.getInputStream());// 关闭输入
                    close(p.getOutputStream());// 关闭输出
                    close(p.getErrorStream());// 关闭error
                    p.destroy();
                }
            } catch (Exception e) {
                LOG.warn("【Ping ERROR】 close process err: ", e);
            }
        }
    }

    private static void close(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (Exception e) {
                LOG.warn("关闭ping异常：" + e.getMessage());
            }
        }
    }

    private static boolean isWindows() {
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            return true;
        }
        return false;
    }

    private static int getCheckResult(String line) {  // System.out.println("控制台输出的结果为:"+line);
        Pattern pattern = Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            return 1;
        }
        return 0;
    }

    private static int getCheckLinuxResult(String line) {  // System.out.println("控制台输出的结果为:"+line);
        Pattern pattern = Pattern.compile("(\\d)(\\s+)(ttl=\\d+)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            return 1;
        }
        return 0;
    }
}
